#include "myfile.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define FILE_MODE 0666

_FILE* _fopen(const char* filename, const char* flag)
{
  int f = 0, fd = -1; 
  if (strcmp(flag, "w") == 0)
  {
     f = (O_CREAT | O_WRONLY | O_TRUNC);
     fd = open(filename, f, FILE_MODE);
  }
  else if (strcmp(flag, "a") == 0) 
  {
     f = (O_CREAT | O_WRONLY | O_APPEND);
     fd = open(filename, f, FILE_MODE);
  }
  else if (strcmp(flag, "r") == 0)
  {
      f = O_RDONLY;
      fd = open(filename, f);
  }
  else 
      return NULL;
  
  if (fd == -1) return NULL;

  _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
  if (fp == NULL) return NULL;
  fp->fileno = fd;
  fp->flag = FLUSH_ALL;
  fp->outPos = 0;

  return fp;
}

int _fwrite(_FILE* fp, const char* s, int len)
{
  memcpy(&fp->outbuffer[fp->outPos], s, len);
  fp->outPos += len;

  if (fp->flag & FLUSH_NOW) // 无刷新
  {
    write(fp->fileno, fp->outbuffer, fp->outPos);
    fp->outPos = 0;
  }
  else if (fp->flag & FLUSH_LINE) // 行刷新
  {
    if (fp->outbuffer[fp->outPos - 1] == '\n')
    {
      write(fp->fileno, fp->outbuffer, fp->outPos);
      fp->outPos = 0;
    }
    else 
    {
      return len;
    }
  }
  else if (fp->flag & FLUSH_ALL) // 全刷新
  {
    if (fp->outPos == SIZE)
    {
      write(fp->fileno, fp->outbuffer, fp->outPos);
      fp->outPos = 0;
    }
    else 
    {
      return len;
    }
  }

  return len;
}

void _fflush(_FILE* fp)
{
  if (fp->outPos > 0)
  {
    write(fp->fileno, fp->outbuffer, fp->outPos);
    fp->outPos = 0;
  }
}

void _fclose(_FILE* fp)
{
  _fflush(fp);
  close(fp->fileno);
  free(fp);
}



//#include <stdio.h>
//#include <stdio.h>
//#include <string.h>
//#include <sys/types.h>
//#include <unistd.h>
//#include <sys/types.h>
//#include <fcntl.h>

//int main()
//{
//  const char* fstr = "hello fwrite\n";
//  const char* str = "hello write\n";
//
//  printf("hello printf\n");
//  sleep(2);
// 
//  fprintf(stdout, "hello fprintf\n");
//  sleep(2);
//  
//  fwrite(fstr, strlen(fstr), 1, stdout);
//  sleep(2);
//  //close(1);
//  write(1, str, strlen(str));
// // fork();
//
//  return 0;
//}
